import { config } from "../config/config";
import { promisic } from "./util";

class Http {
    static async request(params, noRefetch) {
        if (!params.type) {
            params.type = 'GET';
        }
        const res = await promisic(wx.request)({
            url: `${config.apiBaseUrl}${params.url}`,
            data: params.data,
            method: params.type,
            header: {
                'content-type': 'application/json',
                'token': wx.getStorageSync('token')
            }
        })
        const code = res.statusCode.toString();
        const startChar = code.charAt(0);
        if (startChar == '2') {
            return res.data
        } else{
            if (code == '401') {
                if (!noRefetch) {
                    return await this._refetch(params);
                }
                return false;
            }else if(code == '400'){
                for (let tmp in res.data.msg) {
                    wx.showToast({
                        title: res.data.msg[tmp],
                        icon: 'none',
                        duration: 2000
                    })
                }
                return false;
            }
        }
    }

    static async login() {
        const res = await promisic(wx.login)({});
        return res.code
    }

    static async _refetch(params) {
        const code = await this.login();
        const res = await promisic(wx.request)({
            url: `${config.apiBaseUrl}token/user`,
            data: {
                code: code
            },
            method: "POST",
        })
        wx.setStorageSync('token', res.data.token);
        return await this.request(params,true);
    }
}

export {
    Http
}